<?php

namespace XiaoZhuBundle\Controller;

use AdminsBundle\Entity\Product;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use XiaoZhuBundle\Helper\MyController;
/**
 * @Route("/Product")
 */
class ProductController extends MyController
{

    /*快速复制项目通用化配置*/
    private $entity;
    private $entityName = "Product";
    private $listKeys = array("id","title","cid","price","marketPrice",);
    private $searchKeys = array("title");
    private $conditionKeys = array("cid","isIndex");
    private $editKeys = array("");
    private $perPage = 15;

    /**
     * @Route("/List", name="listProduct")
     */
    public function listProduct(Request $request)
    {
        //获取分页信息
        if (!$p = $this->getParamRequired("p",$request)) {$p = 1;}
        if (!$perPage = $request->cookies->get("perPage")) {$perPage = $this->perPage;}
        $param["page"] = $p;
        $param["per_page"] = $perPage > 90 ? 90 : $perPage ;

        //获取筛选信息
        if ($category = $this->getParamRequired("category",$request)) {
            $param["andWhere"]["cid"] = $category;
        }
//        if ($isNew = $this->getParamRequired("isNew",$request)) {
//            $param["andWhere"]["isNew"] = $isNew;
//        }
//        if ($isHot = $this->getParamRequired("isHot",$request)) {
//            $param["andWhere"]["isHot"] = $isHot;
//        }
//        if ($isSale = $this->getParamRequired("isSale",$request)) {
//            $param["andWhere"]["isSale"] = $isSale;
//        }
//        if ($isFamous = $this->getParamRequired("isFamous",$request)) {
//            $param["andWhere"]["isFamous"] = $isFamous;
//        }

        //产品属性筛选
        if ($valIds = $this->getParamRequired("valId",$request)) {
            $param["andWhere"]["attr"] = $valIds;
            $request->cookies->remove("valId");
            $request->cookies->add("valId");
        }
        if ($valIds = $request->cookies->get("valId")) {
            $param["andWhere"]["attr"] = $valIds;
        }

        //获取排序信息
        $param["orderBy"]["id"] = "DESC";
        if ($price = $request->cookies->get("price")) {
            $param["orderBy"]["price"] = $price == 1 ? 1 : 0;
        }
        if ($sell = $request->cookies->get("sell")) {
            $param["orderBy"]["sell"] = $sell == 1 ? 1 : 0;
        }
//        if ($create = $request->cookies->get("create")) {
//            $param["orderBy"]["create"] = $create == 1 ? 1 : 0;
//        }
//        if ($collect = $request->cookies->get("collect")) {
//            $param["orderBy"]["collect"] = $collect == 1 ? 1 : 0;
//        }

        $Model = $this->get("xiao_zhu.product_model");
        $product = $Model->listProduct($param);

        //分页
        $baseUrl = $this->generateUrl("listProduct");
        $first_url = "$baseUrl";
        $pagination = $this->creatPage($first_url,$baseUrl,$Model->countProduct($param),$perPage);
        $data = array(
            "products"   => $product,
            "pagination"   => $pagination,
        );

        //左侧信息获取
        //分类列表
        $Category = $this->get("xiao_zhu.category_model");
        $catTree = $Category->getCategoryTree();
        $data["CatTree"] = $catTree[0]["sons"];
        //所有品牌
        $repAttr = $this->DB("AdminsBundle:CategoryAttribute");
        $mainAttr = $repAttr->findBy(array("cid"=>"1"));
        $repVal = $this->DB("AdminsBundle:CategoryAttributeValue");
        $attrAndValues = array();
        foreach ($mainAttr as $attr) {
            $attrAndValues[] = array(
                "name"  => $attr->getAttrName(),
                "values"=> $repVal->findBy(array("attrId"=>$attr->getId()))
            );
        }
        $data["attrAndValues"] = $attrAndValues;
//        $brands = $repVal->findBy(array("attrId"=>""));
//        var_dump($attrAndValues);
        //热卖商品
        $param = array();
        $param["andWhere"]["isHot"] = 1;
        $param["page"] = 1;
        $param["per_page"] = 10;
        $ProductHot = $Model->listProduct($param);
        $data["ProductHot"] = $ProductHot;
        return $this->render('@XiaoZhu/product_list.html.twig',$data);
    }



    /**
     * @param Request $request
     * @return Response
     * @Route("/Show", name="productShow")
     */
    public function productShowController( Request $request )
    {
        $ProductModel = $this->get("xiao_zhu.product_model");
        //右侧数据
        if (!$id = $this->getParamRequired("id",$request)) {return $this->js_out("小主！你在找什么呀？");}
        $product = $ProductModel->showProduct($id);
        //分类参数处理
        $Category = $this->get("xiao_zhu.category_model");
        $params = $Category->getCategoryFromString($product["searchInfo"]);
        $product["params"] = $params["attr"];
        $data = array();
        $data["product"] = $product;
        //检测评论情况
        $data["comments"] = 0;
        $session = $this->get("session");
        $oldData = $session->get("productStars");
        if (!$oldData) {
            $oldData = array();
        }
        if (array_key_exists($id,$oldData)) {
            $data["comments"] = 1;
        }

        //左侧数据
        //相似商品
        $param = array();
        $param["andWhere"]["cid"] = $product["cid"];
        $param["page"] = 1;
        $param["per_page"] = 5;
        $ProductSame = $ProductModel->listProduct($param);
        $data["ProductSame"] = $ProductSame;

        //最新商品
        $param = array();
        $param["andWhere"]["isNew"] = 1;
        $param["page"] = 1;
        $param["per_page"] = 10;
        $ProductNew = $ProductModel->listProduct($param);
        $data["ProductNew"] = $ProductNew;

        return $this->render('@XiaoZhu/product.html.twig',$data);
    }


    /**
     * @Route("/SubmitStar", name="ProductSubmitStar")
     */
    public function subStar(Request $request)
    {
        //session内产品打分记录格式
        /*
         * 字段名productStars
         * 格式 array
         * 每条记录包含信息
         *      key => val
         *      key = pid
         *      val = score
         * */
        if (!$pid = $this->getParamRequired("pid",$request)) {die("ERROR");}
        if (!$score = $this->getParamRequired("score",$request)) {die("ERROR");}

        $session = $this->get("session");
        if ($session->has("productStars")) {
            $oldData = $session->get("productStars");
            if (!$oldData) {
                $oldData = array();
            }
            //排除恶意评分
            if (count($oldData) > 10 && array_sum($oldData)/count($oldData) < 2) {
                die("ERROR");
            }
            if (!array_key_exists($pid,$oldData)) {
                $newData = $oldData;
                $newData[$pid] = $score;
            } else {
                die("ERROR");
            }
        } else {
            $newData[$pid] = $score;
//            $session->set("productStars" , $newData);
//            return $this->json_out(1,"评分成功");
        }
        //更新数据库数据
        $product = $this->DB("AdminsBundle:ProductStatistic")->find($pid);
        if ($product) {
            $star1 = $product->getStar1();
            $star2 = $product->getStar2();
            $star3 = $product->getStar3();
            $star4 = $product->getStar4();
            $star5 = $product->getStar5();
            switch (ceil($score)) {
                case 1 :
                    $product->setStar1($star1 + 1);
                    $star1++ ;
                    break;
                case 2 :
                    $product->setStar2($star2 + 1);
                    $star2++ ;
                    break;
                case 3 :
                    $product->setStar3($star3 + 1);
                    $star3++ ;
                    break;
                case 4 :
                    $product->setStar4($star4 + 1);
                    $star4++ ;
                    break;
                default:
                    $product->setStar5($star5 + 1);
                    $star5++ ;

            }
            $average = (1*$star1 + 2*$star2 + 3*$star3 + 4*$star4 + 5*$star5)/($star1 + $star2 + $star3 + $star4 + $star5);
            $product->setStars(ceil($average));
            $em = $this->EM();
            $em->persist($product);
            $em->flush();

            //更新session
            $session->set("productStars" , $newData);
            return $this->json_out(1,"评分成功");
        } else {
            die("ERROR");
        }
    }
}
